package com.kkarma.common.exception;

import com.kkarma.common.constants.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: karma
 * @Date: 2022/5/25 0025 - 05 - 25 - 15:26
 * @Description: com.kkarma.common.exception
 * @version: 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public ResponseEntity handleServiceException(ServiceException ex)
    {
        log.error(ex.getMessage(), ex);
        Integer code = ex.getCode();
        return !StringUtils.isEmpty(code) ? ResponseEntity.error(code, ex.getMessage()) : ResponseEntity.error(ex.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ResponseEntity.error(e.getMessage());
    }
}
